<?php
require_once('../../core.inc.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Prefecture.php');
require_once('Model/Pager.php');
require_once('Model/Uploader.php');
require_once('Model/EstateSale.php');

if(get_magic_quotes_gpc()){
    $params = __stripSlash($_REQUEST);    
}
else{
    $params = $_REQUEST;
}
$smarty      = new View_Smarty($params);
$estate_sale = new Model_EstateSale();
$smarty->assign('estate_sale', $estate_sale);

//
require_once( '../../system/libs/Class_DB.php' );
require_once( '../../system/libs/Class_ERROR.php' );
require_once( '../../system/libs/login.inc.php' );
require_once( '../../system/libs/const.php' );
require_once( '../../system/libs/functions.php' );
if( !in_array( MANAGE_ESTATE, $_SESSION['ADMIN_LOGIN']['AUTH_CD'] ) ) exit;
//

if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], $params, $smarty, $estate_sale); 
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, $smarty, $estate_sale);
}
else{
    call_user_func('op_search', $params, $smarty, $estate_sale);
}
//// ajax
function exec_add_image_box($params, &$smarty, &$estate_sale)
{
    $key = time();
    $smarty->assign('key', $key);
    $smarty->assign('hash', sha1('forms[img][3]['.$key.']'));
    echo($smarty->fetch('estate_sale/include/form_detail_add_image_box.inc.html'));
    exit();
}
////
function op_search($params, &$smarty, &$estate_sale)
{
    if (!isset($params['search'])){
        $search = array();
        foreach($estate_sale->getFormKeys() as $key){
            $search[$key] = '';
        }
        $search['interest']  = '';
        $search['date_from'] = '';
        $search['time_from'] = '';
        $search['date_to']   = '';
        $search['time_to']   = '';
        $params['search']    = $search;
    }
    else{
        if ($params['search']['date_from'] != ''){
            $params['search']['st_datetime'] = $params['search']['date_from'] . ' ' . sprintf('%02d', $params['search']['time_from']) . ':00';
        }
        if ($params['search']['date_to'] != ''){
            $params['search']['ed_datetime'] = $params['search']['date_to'] . ' ' . sprintf('%02d', $params['search']['time_to']) . ':00';
        }
        $page_id = isset($params['page_id']) && $params['page_id'] > 1 ? $params['page_id'] : 1;
        $max_row = 20;
        $pager   = new Model_Pager();
        $pager->getPagerInfo($estate_sale->getListCount($params['search']), $page_id, $max_row);
        $list = $estate_sale->getList($params['search'], 'id asc', $max_row, ($max_row * ($page_id - 1)));
        $smarty->assign('list', $list);
        $smarty->assign('pager', $pager);
    }
    $params['search']['status']      = isset($params['search']['status']) ? $params['search']['status'] : array();
    $params['search']['class_id']    = isset($params['search']['class_id']) ? $params['search']['class_id'] : array();
    $params['search']['category_id'] = isset($params['search']['category_id']) ? $params['search']['category_id'] : array();

    $smarty->assign('search', $params['search']);
    $smarty->display('estate_sale/estate_sale_index.html');
}
// 新規登録
function op_regist($params, &$smarty, &$estate_sale)
{
    if (!isset($params['forms'])){
        $forms = array();
        foreach($estate_sale->getFormKeys() as $key){
            $forms[$key] = '';
        }
        $forms['zipcode1'] = '';
        $forms['zipcode2'] = '';
        $forms['st_date']  = '';
        $forms['st_time']  = 0;
        $forms['ed_date']  = '';
        $forms['ed_time']  = 0;
        $forms['years_y']  = '';
        $forms['years_m']  = '';
        $params['forms']   = $forms;
    }
    else{
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
    }
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('estate_sale/estate_sale_form.html');
//print_r($params);
}
function exec_validate_regist_form(&$params, &$smarty, &$estate_sale)
{
    $err = array();
    // 詳細画像の空削除
    if(isset($params['forms']['img'])){
        if(isset($params['forms']['img'][3])){
            foreach($params['forms']['img'][3] as $n => $cache){
                if($cache == '' && (!isset($params['forms']['img_comment'][3][$n]) || $params['forms']['img_comment'][3][$n] == '')){
                    unset($params['forms']['img'][3][$n]);
                    unset($params['forms']['img_comment'][3][$n]);
                }
            }
        }
    }
    //
    if ($estate_sale->validate($params['forms'], $err)){
        return exec_regist_form($params, $smarty, $estate_sale);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
print_r($err);
    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$estate_sale)
{
    $params['forms']['zip_code']    = ($params['forms']['zipcode1'] != '' && $params['forms']['zipcode2'] != '' ? $params['forms']['zipcode1'].'-'.$params['forms']['zipcode2']   : '');
    $params['forms']['years']       = ($params['forms']['years_y']  != '' && $params['forms']['years_m']  != '' ? sprintf('%04d-%02d-01', $params['forms']['years_y'], $params['forms']['years_m']) : '');
    $params['forms']['st_datetime'] = ($params['forms']['st_date']  != '' && $params['forms']['st_time']  != '' ? $params['forms']['st_date'].' '.sprintf('%02d:00', $params['forms']['st_time']) : '');
    $params['forms']['ed_datetime'] = ($params['forms']['ed_date']  != '' && $params['forms']['ed_time']  != '' ? $params['forms']['ed_date'].' '.sprintf('%02d:00', $params['forms']['ed_time']) : '');
    $id = $estate_sale->insert($params['forms']);
    // img
    if(isset($params['forms']['img'])){
        $uploader = new Model_Uploader();
        foreach($params['forms']['img'] as $type => $img){
            foreach($img as $key => $cache){
                if($cache != ''){
// 本来 site_id で振り分け
$base_name = $id . '_' . $type; 
$move_to   = SiteManageRootDir . '/htdocs/investment/images/';
//
                    $filename = $uploader->moveCacheImage($cache, $move_to, $base_name);
                    $data = array(
                            'estate_sale_id' => $id,
                            'type'           => $type,
                            'filename'       => $filename,
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                            );
                    $img_id = $estate_sale->insertImage($data);
                }
            }
        }
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id);
    exit();
}
function op_regist_complete($params, &$smarty, &$estate_sale)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('estate_sale/estate_sale_form.html');
}
// 編集
function op_edit($params, &$smarty, &$estate_sale)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms = $estate_sale->get($id);
        $forms['zipcode1'] = !empty($forms['zip_code']) ? substr($forms['zip_code'], 0, 3) : '';
        $forms['zipcode2'] = !empty($forms['zip_code']) ? substr($forms['zip_code'], 4, 4) : '';
        $forms['st_date']  = !empty($forms['st_datetime']) ? substr($forms['st_datetime'], 0, 10) : '';
        $forms['st_time']  = !empty($forms['st_datetime']) ? substr($forms['st_datetime'], 12, 2) : '0';
        $forms['ed_date']  = !empty($forms['ed_datetime']) ? substr($forms['ed_datetime'], 0, 10) : '';
        $forms['ed_time']  = !empty($forms['ed_datetime']) ? substr($forms['ed_datetime'], 12, 2) : '0';
        $forms['years_y']  = !empty($forms['years']) ? substr($forms['years'], 0, 4) : '';
        $forms['years_m']  = !empty($forms['years']) ? substr($forms['years'], 5, 2) : '';
        $forms['img']         = array();
        $forms['img_comment'] = array();
        foreach($estate_sale->getImageList($id) as $data){
// 本来は site_id で振り分け
$forms['img'][$data['type']][] = 'http://investment.bird-i.co.jp/images/' . $data['filename'];
if($data['type'] == 3){
    $forms['img_comment'][3][] = $data['comment'];
} 
        }
        $params['forms']   = $forms;
    }
    else{
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
    }
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('estate_sale/estate_sale_form.html');
}
function exec_validate_update_form(&$params, &$smarty, &$estate_sale)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $err = array();
    // 詳細画像の空削除
    if(isset($params['forms']['img'])){
        if(isset($params['forms']['img'][3])){
            foreach($params['forms']['img'][3] as $n => $cache){
                if($cache == '' && (!isset($params['forms']['img_comment'][3][$n]) || $params['forms']['img_comment'][3][$n] == '')){
                    unset($params['forms']['img'][3][$n]);
                    unset($params['forms']['img_comment'][3][$n]);
                }
            }
        }
    }
    //
    if ($estate_sale->validate($params['forms'], $err)){
        return exec_update_form($params, $smarty, $estate_sale);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'regist';
}
function exec_update_form(&$params, &$smarty, &$estate_sale)
{
    $id = $params['id'];
    
	if($_POST['mode'] == "delete")
	{
		$params['forms']['enabled'] = 0;
	}
	
    $params['forms']['zip_code']    = ($params['forms']['zipcode1'] != '' && $params['forms']['zipcode2'] != '' ? $params['forms']['zipcode1'].'-'.$params['forms']['zipcode2']   : '');
    $params['forms']['years']       = ($params['forms']['years_y']  != '' && $params['forms']['years_m']  != '' ? sprintf('%04d-%02d-01', $params['forms']['years_y'], $params['forms']['years_m']) : '');
    $params['forms']['st_datetime'] = ($params['forms']['st_date']  != '' && $params['forms']['st_time']  != '' ? $params['forms']['st_date'].' '.sprintf('%02d:00', $params['forms']['st_time']) : '');
    $params['forms']['ed_datetime'] = ($params['forms']['ed_date']  != '' && $params['forms']['ed_time']  != '' ? $params['forms']['ed_date'].' '.sprintf('%02d:00', $params['forms']['ed_time']) : '');
    $estate_sale->update($id, $params['forms']);
    // img
    if(isset($params['forms']['img'])){
        $registed = array();
        foreach($estate_sale->getImageList($id) as $data){
            $registed[$data['type']][$data['filename']] = $data;
        }
        $uploader = new Model_Uploader();
        foreach($params['forms']['img'] as $type => $img){
            foreach($img as $key => $cache){
                if($cache != '' && !preg_match('/http/', $cache)){
// 本来 site_id で振り分け
$base_name = $id . '_' . $type;
$move_to   = SiteManageRootDir . '/htdocs/investment/images/';
//
                    $filename = $uploader->moveCacheImage($cache, $move_to, $base_name);
                    $data = array(
                            'estate_sale_id' => $id,
                            'type'           => $type,
                            'filename'       => $filename,
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                    );
                    if(($type == 1 || $type == 2) && isset($registed[$type])){
                        $estate_sale->updateImage($data);
                    }
                    else{
                        $img_id = $estate_sale->insertImage($data);
                    }
                }
                elseif($type == 3){
                    // コメント更新
                    $data = array(
                            'estate_sale_id' => $id,
                            'type'           => $type,
                            'filename'       => array_pop(explode('/',$cache)),
                            'comment'        => (isset($params['forms']['img_comment'][$type][$key]) ? $params['forms']['img_comment'][$type][$key] : '')
                    );
                    $estate_sale->updateImageComment($data);
                }
            }
        }
        // type = 3 削除
        foreach($img as $cache){
            if(preg_match('/http/', $cache)){
                $filename = array_pop(explode('/', $cache));
                if(isset($registed[3][$filename])){
                    unset($registed[3][$filename]);
                }
            }
        }
        if(!empty($registed[3])){
            foreach($registed[3] as $filename => $data){
                $estate_sale->deleteImageById($data['id']);
            }
        }
        //
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id);
    exit();
}
function op_edit_complete($params, &$smarty, &$estate_sale)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('estate_sale/estate_sale_form.html');
}

?>